package com.lqq.school.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lqq.school.domain.User;
import com.lqq.school.mapper.UserMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class UserController {
    @Resource
    private UserMapper userMapper;

    @GetMapping("/toUser")
    public String userList(Model model) {
        List<User> users = userMapper.selectList(null);
        model.addAttribute("list", users);
        return "/admin/userlist";
    }

    @GetMapping("/toAddUser")
    public String toAddUser() {
        return "/admin/useradd";
    }

    @PostMapping("/addUser")
    public String addUser(User user, Model model) {
        System.out.println(user);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", user.getUsername());

        if (userMapper.selectOne(queryWrapper) == null) {
            System.out.println("插入数据！！!");
            userMapper.insert(user);
            return "/admin/dashboard";
        }
        else {
            model.addAttribute("msg", "用户存在，新增失败！！！");
            return "/admin/useradd";
        }
    }

    @GetMapping("/toDelete/{id}")
    public String delete(@PathVariable("id") Long id) {

        int delete = userMapper.deleteById(id);
        if (delete > 0) {
            System.out.println("删除用户成功！");
        }

        return "redirect:/toUser";
    }
}
